﻿package domino{
	//import fl.controls.Button;
	
	
	
   
 
  import flash.ui.Keyboard;

	import flash.display.*;
	import flash.events.*;
	import flash.geom.Point;
	import flash.text.*;
	import flash.utils.Timer;
	import flash.events.TimerEvent;
	import Box2D.Dynamics.*;
	import Box2D.Collision.*;
	import Box2D.Collision.Shapes.*;
	import Box2D.Common.Math.*;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	public class domino extends MovieClip {
		
		public var mousePVec:b2Vec2 = new b2Vec2();
		public var real_x_mouse:Number;
		public var real_y_mouse:Number;
		public var m_world:b2World;
		
		public var pixels_in_a_meter = 30;
		public var physScale:Number = 30;
		public var m_iterations:int = 10;
		public var m_timeStep:Number = 1/30;
		public var gravity:b2Vec2 = new b2Vec2(0.0, 10.0);
		public var body_number:int;
		
		public var the_world:b2World;
		public var dominNumber:int=-1;
		public var dominArray:Array;
		
		public var redact:Boolean = false;
		var moveable:Boolean = false;
		var domin:actor;
		var walls:actorWall;
		var circle:actorCircle;
		var run:Boolean=false;
		var PointArray:Array;
		var wallArray:Array;
		var arrowSprite:Sprite;
		var aboveMouse:b2Body;
		var centerPos:b2Vec2;
		var actDomin:actor;
		var typeOfFigure:int = 0;
		var numberOfType:int = 2;
		var Levels:XML;
		var levelsDoc:XML;
		var urlLoad:URLLoader;
		var IO_XML:IOXML;
		var figures:Array;
		var stat:Boolean=false;
		var button_click:Boolean = false;
		var main_level:int = -1;
		var urlReq:URLRequest;
		var a:Array = new Array();
		var b:Array = new Array();
		var m:Boolean = true;
		var temp_domin:actor;
		/////buttons
		var redactor_button:SimpleButton = new BRedactor();
		var levels_button:SimpleButton= new BLevels();
		var help_button:SimpleButton = new BHelp;;
		var brun:SimpleButton = new Run();
		var start_button:SimpleButton = new BStart();
		var	bsave:SimpleButton = new Save();
		var bmove:SimpleButton = new Move();
		
		var	bclear:SimpleButton = new Clear();
		var	bRemoveObj:SimpleButton = new RemoveObj();

		public var main_menu:Menu = new Menu();
		public var main_restart:Restart = new Restart();
		
		var edit_scaleX:TextField = new TextField();
		var edit_scaleY:TextField = new TextField();
		var edit_X:TextField = new TextField();
		var edit_Y:TextField = new TextField();
		var edit_angle:TextField = new TextField();
		var edit_restitution:TextField = new TextField();
		var edit_density:TextField = new TextField();
		var edit_friction:TextField = new TextField();
		var edit_angV:TextField = new TextField();
		var clicks:TextField = new TextField();
		
		var edit_main:Sprite = new Sprite();
		var format1:TextFormat = new TextFormat();
		var figureTypes:Array= new Array();
        var iconArray:Array = new Array(); 
		
		var typeFigure:String = "";
		var coins:int=0;
		var target:int=20;
		var isSensor:int = 0;
		
		//edit_scaleX.type=i
		
		///////////////////////////////////
		var level:TextField = new TextField();
		var target_coin:TextField = new TextField();
		var coin:TextField = new TextField();
		
		public var dominToDelete:Array;
		///
		/////////////////////////////
	
public function domino() {
			
			 
			 this.stop();
			 stop();
			addArrow();
			addCoord();
			addTypes();
			
			addButtonsMenu();
			addButtonsRedactor();
			addlevelButton();//

			dominArray = [];
			dominToDelete = [];

			createWorld();
			//walls = new actorWall(m_world, this, new Point(0, 0), wallArray,false);
		    //dominArray.push(walls);

		     hideRedactor();
		     viewMenu();
		     hideLevels();
			//createDebugDraw();
       	     IO("test.xml");
		    
		    addEventListener(MainField.MOUSE_IN_FIELD, fieldHandler);
			addEventListener(MainField.MOUSE_IN_FIGURES, menuHandler);
			addEventListener(MainField.MOUSE_IN_SELECT, selectHandler);
			
			addEventListener(Event.ENTER_FRAME, Update);
			
			stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressedDown);
			//stage.addEventListener(KeyboardEvent.KEY_DOWN, TextFieldListener2);
			
			stage.addEventListener(MouseEvent.CLICK,clickListener);
			
		}
		
		
///////////////////////////////////////////////
private function LoadLevel(num:int) {
		actDomin = null;
		temp_domin = null;
		figures = IO_XML.getFigures(num);
		clicks.text = String(Number(figures[0][12]));
		
		      for each(var figure:Array in figures) {
				  
				  
	              if(figure[2] == "triangle"){
				    domin = new actorTriangle(m_world, this, new Point(figure[0], figure[1]),figure[3], figure[4], figure[5],figure[6],figure[7],figure[9],figure[11]);	
					dominArray.push(domin);
					domin.addEventListener(OutOfScreen.OUT_DOMIN,removeHandler);
					continue;
				  }
				  
				  if(figure[2] == "domino"){
				    domin = new actorDomino(m_world, this, new Point(figure[0], figure[1]),figure[3], figure[4], figure[5],figure[6],figure[7],figure[9],figure[11]);	
					dominArray.push(domin);
					domin.addEventListener(OutOfScreen.OUT_DOMIN,removeHandler);
					continue;
				  }
				  
				  if (figure[2] == "circle") {
		             domin = new actorCircle(m_world, this, new Point(figure[0], figure[1]),figure[3], figure[4], figure[5],figure[6],figure[7],figure[9],figure[11]);
					 dominArray.push(domin);
					 domin.addEventListener(OutOfScreen.OUT_DOMIN,removeHandler);
					 continue;
				  }
					 
				  if (figure[2] == "cross") {
		             domin = new actorCross(m_world, this, new Point(figure[0], figure[1]),figure[3], figure[4], figure[5],figure[6],figure[7],figure[9],figure[10],figure[11]);
					 dominArray.push(domin);
					 continue;	 
				  }
				  
				  if (figure[2] == "angle") {
		             domin = new actorAngle(m_world, this, new Point(figure[0], figure[1]),figure[3], figure[4], figure[5],figure[6],figure[7],figure[9],figure[10],figure[11]);
					 dominArray.push(domin);
					 continue;	 
				  }
				  
				  if (figure[2] == "trident") {
		             domin = new actorTrident(m_world, this, new Point(figure[0], figure[1]),figure[3], figure[4], figure[5],figure[6],figure[7],figure[9],figure[10],figure[11]);
					 dominArray.push(domin);
					 continue;	 
				  }
				  
				  if (figure[2] == "trident2") {
		             domin = new actorTrident2(m_world, this, new Point(figure[0], figure[1]),figure[3], figure[4], figure[5],figure[6],figure[7],figure[9],figure[10],figure[11]);
					 dominArray.push(domin);
					 continue;	 
				  }
				 
				  if (figure[2] == "pendulum") {
		             domin = new actorPendulum(m_world, this, new Point(figure[0], figure[1]),figure[3], figure[4], figure[5],figure[6],figure[7],figure[9],figure[10],figure[11]);
					 dominArray.push(domin);
					 continue;	 
				  }
				  
				  if (figure[2] == "pendulum2") {
		             domin = new actorPendulum2(m_world, this, new Point(figure[0], figure[1]),figure[3], figure[4], figure[5],figure[6],figure[7],figure[9],figure[10],figure[11]);
					 dominArray.push(domin);
					 continue;	 
				  }
				  
				  if (figure[2] == "coin") {
		             domin = new actorCoin(m_world, this, new Point(figure[0], figure[1]),figure[3], figure[4], figure[5],figure[6],figure[7],figure[9]);
					 domin.addEventListener(takeCoin.TAKE_COIN,coinHandler);
					 dominArray.push(domin);
					 coins = figure[8];
					 //trace(coins);
					 
					 continue;
				  }
				  
				   throw new Error("Error of IO");
				
			  }
		}
////////////////////////////////////////////////////////////////	
function addTypes() {
	figureTypes.push("actorDomino");
	figureTypes.push("actorCircle");
	figureTypes.push("actorCross");
	figureTypes.push("actorWall");
	figureTypes.push("actorCoin");
	figureTypes.push("actorAngle");
	figureTypes.push("actorTrident");
	figureTypes.push("actorTrident2");
	figureTypes.push("actorPendulum");
	figureTypes.push("actorPendulum2");
	figureTypes.push("actorTriangle");
	
	

	}
////////////////////////////////////////////////////////////
function addIcons() {
  
	
	var iconDomino:actorDomino = new actorDomino(m_world, this, new Point(660, 55), 0,0, 0.3, 0.5, 0.5,0,0);	
	iconArray.push(iconDomino);
	
	var iconCircle:actorCircle= new actorCircle(m_world, this, new Point(675,55),0,0,0.3,0.5,0.5,0,0);		
	iconArray.push(iconCircle);
	
	var iconCross:actorCross = new actorCross(m_world, this, new Point(710, 51), 0, 0, 0.3, 0.5, 0.5,0,0,0);
	iconArray.push(iconCross);
	
	var iconCoin:actorCoin= new actorCoin(m_world, this, new Point(665,83),0,0,0.3,0.5,0.5,0);		
	iconArray.push(iconCoin);
	
	var iconAngle:actorAngle = new actorAngle(m_world, this, new Point(675, 83), 0, 0, 0.3, 0.5, 0.5,0,0,0);
	iconArray.push(iconAngle);
	
	var iconTrident:actorTrident = new actorTrident(m_world, this, new Point(720, 103), 0, 0, 0.3, 0.5, 0.5,0,0,0);
	iconArray.push(iconTrident);
	
	var iconTrident2:actorTrident2 = new actorTrident2(m_world, this, new Point(690, 115), 0, 0, 0.3, 0.5, 0.5,0,0,0);
	iconArray.push(iconTrident2);
	
	var iconPendulum:actorPendulum = new actorPendulum(m_world, this, new Point(725, 55), 0, 0, 0.3, 0.5, 0.5,0,0,0);
	iconArray.push(iconPendulum);
	
	var iconPendulum2:actorPendulum2 = new actorPendulum2(m_world, this, new Point(720, 115), 0, 0, 0.3, 0.5, 0.5,0,0,0);
	iconArray.push(iconPendulum2);
	
	var iconTriangle:actorTriangle = new actorTriangle(m_world, this, new Point(745, 115), 0, 0, 0.3, 0.5, 0.5,0,0);
	iconArray.push(iconTriangle);
	
}
//////////////////////////////////
private function keyPressedDown(event:KeyboardEvent):void {
      var key:uint = event.keyCode;
      var step:uint = 5;
      switch (key) {
          case Keyboard.LEFT :
       if (moveable){
	      edit_X.text = String(Number(edit_X.text) - 5); 
		  if(actDomin)
		   //reloadDomin();
		   recreateDomin();
	  }
	   //actDomin.move(-5,0);
       else
	   {
		 edit_angle.text = String(Number(edit_angle.text) - 6); 
		   //actDomin.rotate(9);
		 if(actDomin)
		 recreateDomin();  
		 //reloadDomin();
	   }
	   break;
          case Keyboard.RIGHT :
	   if (moveable){
	       edit_X.text = String(Number(edit_X.text) + 5); 
		  //actDomin.move(5,0);
	     if(actDomin)
		 recreateDomin();  
		 //reloadDomin();
		  }
       else {
            //actDomin.rotate( -9);
		   edit_angle.text = String(Number(edit_angle.text) + 6); 
			if(actDomin)
		    recreateDomin(); 
			//reloadDomin();
			}
            break;
          case Keyboard.UP :
		if (moveable){
	     edit_Y.text = String(Number(edit_Y.text) - 5); 
		 if(actDomin)
		 recreateDomin();  
		 //reloadDomin();
		 }
		//  actDomin.move(0,-5);
          else
		  {;}
		  break;
          case Keyboard.DOWN :
          if (moveable){
	        edit_Y.text = String(Number(edit_Y.text) + 5); 
		  if(actDomin)
		  recreateDomin(); 
		  //reloadDomin();
			}
		  //actDomin.move(0,5);
          else
	      ;
		  //player.y += step;
            break;
      }
    }
//////////////////////////////////////////////
function hideMenu() {		
			redactor_button.visible = false;		
			};
///////////////////////////////////////////////	
function viewMenu() {
			redactor_button.visible = true;	
			};
////////////////////////////////////////
public function addButtonsMenu() {
			
			redactor_button.x = 275;
			redactor_button.y = 104;
			stage.addChild(redactor_button);
		    redactor_button.addEventListener(MouseEvent.CLICK, bredactorHandler);
					
			m = false;
	}
/////////////////////////////
public function addButtonsRedactor() {
			
		     
		     format1.font="Rockwell Extra Bold";
             format1.bold = true;
			 format1.size = 16;

	        //redactor buttons
	        brun.x = 40;
			brun.y = 12;
			stage.addChild(brun);
			brun.addEventListener(MouseEvent.CLICK, brunHandler);
			
			bsave.x = 176;
			bsave.y = 12;
			stage.addChild(bsave);
			bsave.addEventListener(MouseEvent.CLICK, bsaveHandler);
			
			
			bmove.x = 244;
			bmove.y = 12;
			stage.addChild(bmove);
			bmove.addEventListener(MouseEvent.CLICK, bmoveHandler);

			bclear.x = 108;
			bclear.y = 12;
			stage.addChild(bclear);
			bclear.addEventListener(MouseEvent.CLICK, bclearHandler);
			
			bRemoveObj.x = 312;
			bRemoveObj.y = 12;
			stage.addChild(bRemoveObj);
			bRemoveObj.addEventListener(MouseEvent.CLICK, bremoveObjHandler);
			
			level.x = 728;
		    level.y = 8;
			level.setTextFormat(format1);
			level.textColor = 0xFF0000;
			level.type = TextFieldType.DYNAMIC;
		    level.text = String(main_level);
		    stage.addChild(level);
			
			target_coin.x = 715;
		    target_coin.y = 325;
			target_coin.setTextFormat(format1);
			target_coin.textColor = 0xFF0000;
			target_coin.type = TextFieldType.DYNAMIC;
		    target_coin.text = String(target);
		    stage.addChild(target_coin);
			
			coin.x = 700;
		    coin.y = 340;
			coin.setTextFormat(format1);
			coin.textColor = 0xFF0000;
			coin.type = TextFieldType.DYNAMIC;
		    coin.text = String(coins);
		    stage.addChild(coin);
			
			
			
			main_menu.x = 724;
			main_menu.y = 404;
			stage.addChild(main_menu);
			main_menu.addEventListener(MouseEvent.CLICK, bmenuHandler);
			
			
			main_restart.x = 724;
			main_restart.y = 380;
			stage.addChild(main_restart);
			main_restart.visible = false;
			main_restart.addEventListener(MouseEvent.CLICK, restartHandler);
			
			edit_main.x = 688;
			edit_main.y = 235;
			stage.addChild(edit_main);
			
			edit_angV.x = 688;
			edit_angV.y = 206;
		    edit_angV.maxChars = 6;
			edit_angV.width = 27;
            edit_angV.height = 18;
            edit_angV.background = true;
            edit_angV.border = true;
			edit_angV.type = TextFieldType.INPUT;
			stage.addChild(edit_angV);
			edit_angV.visible = true;
			edit_angV.addEventListener(FocusEvent.FOCUS_OUT,TextFieldListener);
			
			edit_scaleX.x = 0;
			edit_scaleX.y = 20;
		    edit_scaleX.maxChars = 6;
			edit_scaleX.width = 27;
            edit_scaleX.height = 18;
            edit_scaleX.background = true;
            edit_scaleX.border = true;
			edit_scaleX.type = TextFieldType.INPUT;
			edit_main.addChild(edit_scaleX);
			edit_scaleX.visible = true;
			edit_scaleX.addEventListener(FocusEvent.FOCUS_OUT,TextFieldListener);
			
			edit_scaleY.x = 50;
			edit_scaleY.y = 20;
		    edit_scaleY.maxChars = 6;
			edit_scaleY.width = 27;
            edit_scaleY.height = 18;
            edit_scaleY.background = true;
            edit_scaleY.border = true;
			edit_scaleY.type = TextFieldType.INPUT;
			edit_main.addChild(edit_scaleY);
			edit_scaleY.visible = true;
			edit_scaleY.addEventListener(FocusEvent.FOCUS_OUT,TextFieldListener);
			
			edit_X.x = 0;
			edit_X.y = 0;
		    edit_X.maxChars = 6;
			edit_X.width = 27;
            edit_X.height = 18;
            edit_X.background = true;
            edit_X.border = true;
			edit_X.type = TextFieldType.INPUT;
			edit_main.addChild(edit_X);
			edit_X.visible = true;
			edit_X.addEventListener(FocusEvent.FOCUS_OUT,TextFieldListener);
			
			edit_Y.x = 50;
			edit_Y.y = 0;
		    edit_Y.maxChars = 6;
			edit_Y.width = 27;
            edit_Y.height = 18;
            edit_Y.background = true;
            edit_Y.border = true;
			edit_Y.type = TextFieldType.INPUT;
			edit_main.addChild(edit_Y);
			edit_Y.visible = true;
			edit_Y.addEventListener(FocusEvent.FOCUS_OUT,TextFieldListener);
			
			edit_angle.x = 0;
			edit_angle.y = 60;
		    edit_angle.maxChars = 6;
			edit_angle.width = 27;
            edit_angle.height = 18;
            edit_angle.background = true;
            edit_angle.border = true;
			edit_angle.type = TextFieldType.INPUT;
			edit_main.addChild(edit_angle);
			edit_angle.visible = true;
			edit_angle.addEventListener(FocusEvent.FOCUS_OUT, TextFieldListener);
			
			edit_restitution.x = 50;
			edit_restitution.y = 60;
		    edit_restitution.maxChars = 6;
			edit_restitution.width = 27;
            edit_restitution.height = 18;
            edit_restitution.background = true;
            edit_restitution.border = true;
			edit_restitution.type = TextFieldType.INPUT;
			edit_main.addChild(edit_restitution);
			edit_restitution.visible = true;
			edit_restitution.addEventListener(FocusEvent.FOCUS_OUT,TextFieldListener);
			
			
			edit_density.x = 0;
			edit_density.y = 40;
		    edit_density.maxChars = 6;
			edit_density.width = 27;
            edit_density.height = 18;
            edit_density.background = true;
            edit_density.border = true;
			edit_density.type = TextFieldType.INPUT;
			edit_main.addChild(edit_density);
			edit_density.visible = true;
			edit_density.addEventListener(FocusEvent.FOCUS_OUT,TextFieldListener);
			
			edit_friction.x = 50;
			edit_friction.y = 40;
		    edit_friction.maxChars = 6;
			edit_friction.width = 27;
            edit_friction.height = 18;
            edit_friction.background = true;
            edit_friction.border = true;
			edit_friction.type = TextFieldType.INPUT;
			edit_main.addChild(edit_friction);
			edit_friction.visible = true;
			edit_friction.addEventListener(FocusEvent.FOCUS_OUT, TextFieldListener);
			
			clicks.x = 0;
			clicks.y = 80;
		    clicks.maxChars = 6;
			clicks.width = 27;
            clicks.height = 18;
            clicks.background = true;
            clicks.border = true;
			clicks.type = TextFieldType.INPUT;
			edit_main.addChild(clicks);
			clicks.visible = true;
			//edit_friction.addEventListener(FocusEvent.FOCUS_OUT,TextFieldListener);
			
			 
		   
		    
		
			
		}
////////////////////////////////	
function hideRedactor() {
		    brun.visible = false;
			bsave.visible = false;
			bmove.visible = false;
		    main_menu.visible = true;  
			bclear.visible = false;
			bRemoveObj.visible = false;
            coin.visible = false;
			target_coin.visible = false;
			level.visible = false;
			edit_restitution.visible = false;
			edit_main.visible = false;
			edit_angV.visible = false;
		}		
////////////////////////////////	
function viewRedactor() { 
			brun.visible=true;
			bsave.visible = true;
			bmove.visible = true;
	        main_menu.visible = true;  
			main_restart.visible = true;  
			bclear.visible = true;
			bRemoveObj.visible = true;
            coin.visible = true;
			target_coin.visible = true;
			edit_restitution.visible = true;
 			level.visible = true;
			edit_main.visible = true; 
			edit_angV.visible = true;
		    addIcons();
		}
////////////////////////////////////
private function addlevelButton() {
		
		
		for (var i:int =0; i < 20; i++ ){
			a.push(new LevButton());
			b.push(new TextField());
			
			b[i].text=String(i);
			b[i].x = 160 + int(i % 5) * 50;
			b[i].y = 85 + int(i/5) * 50;
			a[i].text = String(i);
			a[i].x = 150+ int(i%5) * 50;
			a[i].y = 100 + int(i / 5) * 50;
			
			a[i].addEventListener(MouseEvent.CLICK, levelHandler);
	
			  addChild(b[i]);
			  addChild(a[i]);
		  }
		}
//////////////////////////////////////	
function hideLevels() {
		 for (var i:int = 0; i < 20; i++ ) {
				a[i].visible = false;
				b[i].visible=false;
				}
		}
//////////////////////////////////////	
function viewLevels() {
		 for (var i:int = 0; i < 20; i++ ) {
				a[i].visible = true;
				b[i].visible= true;
				}
		}
//////////////////////////////////// Main menu
private function blevelsHandler(event:MouseEvent) {
		button_click = true;
		viewLevels();
		hideRedactor();
		hideMenu();
		main_menu.visible = true;  
		addlevelButton();
		}
///////////////////////////////////
function TextFieldListener(event:FocusEvent) {
		if ((iconArray.indexOf(actDomin) == -1) && (actDomin is actor))
		{
			trace(actDomin);
		 recreateDomin();
		}
		else
		 trace("select domin for recreating");
		}
///////////////////////////////////
function menuHandler(event:MainField) {
	 aboveMouse = GetBodyAtMouse();
	 
	if(aboveMouse)
	 actDomin = aboveMouse.GetUserData();
	else
	;
	// actDomin = null;
	 
	if(actDomin){
	 trace("we select figure" + actDomin);
	 fillEditBoxes();
	 typeFigure = actDomin.toString();

	 }
	else
	 trace("select some figure");
	}
///////////////////////////////////
function fieldHandler(event:MainField) {
	
	aboveMouse = GetBodyAtMouse();
	//trace(aboveMouse);
	
	if(aboveMouse){
	actDomin = aboveMouse.GetUserData();
	typeFigure = actDomin.toString();
	
	}
	else
	 createDomin();
	 
	if(actDomin){
		 setDominColor();	
		 trace ("we selected this body " + actDomin);	   
		 fillEditBoxes();
	 }
	
	}	
//////////////////////////////////
private function selectHandler(e:MainField):void 
		{
		 trace("select selectable figure ");	
		 aboveMouse = GetBodyAtMouse();
	//trace(aboveMouse);

	if(aboveMouse){
	actDomin = aboveMouse.GetUserData();
	typeFigure = actDomin.toString();

	}
	else
	 createDomin();
	 
	if(actDomin){
		 setDominColor();	
		 trace ("we selected this body " + actDomin);	   
		 fillEditBoxes();
	 }
		}
////////////////////////////////////
function TextFieldListener2(event:FocusEvent) {
		if((iconArray.indexOf(actDomin)==-1)&&(actDomin is actor))
		 reloadDomin();
		else
		trace("select domin for reload");
		}
////////////////////////////////////
function levelHandler(event:MouseEvent) {
				button_click = true;
				main_level = int(event.currentTarget.text);
				level.text = String(main_level);
				run = false;
                 hideLevels();
				 gotoAndStop("new");
				
				 redact = true;
				 
				 viewRedactor();
				 IO("test.xml");
				LoadLevel(main_level);
				//trace(coins);
				  coin.text = String(coins);

			}	
///////////////////////////////////		
function bmenuHandler(event:MouseEvent) {	
			 button_click = true;
			 redact = false;	
			 actDomin = null;
			 gotoAndStop("MMenu");
			
			 hideRedactor();
			 hideLevels();
			 viewMenu();
			  main_menu.visible = false;  
			  main_restart.visible = false; 
			  removeDominos();
			}	
///////////////////////////////////		
function restartHandler(event:MouseEvent) {	
			  button_click = true;
			  hideLevels();
			  removeDominos();
			  run = false;
			  IO("test.xml");
			  LoadLevel(main_level);
			  //trace(coins);
			    coin.text = String(coins);
			}	

	
//////////////////////////////////	
function bclearHandler(event:MouseEvent) {
				button_click = true;
				 // dominToDelete = new Array();
				  dominToDelete.splice(0);
				  removeDominos();
				}
//////////////////////////////////		
function bremoveObjHandler(event:MouseEvent) {
				button_click = true;
				if (actDomin != null){
				   //if((actDomin is actorAngle)||(actDomin is actorDomino)||(actDomin is actorCircle)||(actDomin is actorCross)||(actDomin is actorCoin))
					if(actDomin is actor)
				     if(dominArray.indexOf(actDomin)!=-1) 
				      dominToDelete.push(actDomin); 
				 
				}
				else
				 trace("select some shape please");
			}		
//////////////////////////////////
function bmoveHandler(event:MouseEvent) {
				button_click = true;
				 if(moveable)
		          moveable = false;
		         else
		          moveable = true;
		     }	
//////////////////////////////////
function bredactorHandler(event:MouseEvent) {
				button_click = true;
				hideRedactor();
				hideMenu();
				viewLevels(); 
			 }
//////////////////////////////////
function brunHandler(event:MouseEvent) {
			   button_click = true;
		    if(run)
		     run = false;
		    else {
		     actDomin = null;
				run = true;
			}
		   }
////////////////////////////////////	
function bsaveHandler(event:MouseEvent) {
				button_click = true;
			    IO_XML.saveLevel(dominArray, main_level,Number(clicks.text));
			}	
////////////////////////////////////
public function createDebugDraw():void {
		    var debug_draw:b2DebugDraw = new b2DebugDraw();
	        var debug_sprite:Sprite = new Sprite();
			
		    addChild(debug_sprite);
			
			debug_draw.m_sprite=debug_sprite;
			debug_draw.m_drawScale=30;
			debug_draw.m_fillAlpha=0.5;
			debug_draw.m_lineThickness=1;
			debug_draw.m_drawFlags=b2DebugDraw.e_shapeBit;
			m_world.SetDebugDraw(debug_draw);
		}
///////////////////////////////////
function recreateDomin() {
		
		   if (actDomin != null){
				if(actDomin is actor)   
			     dominToDelete.push(actDomin); 
		   }
		
		
		if(actDomin is actorTriangle){
		             domin = new actorTriangle(m_world, this, new Point(Number(edit_X.text), Number(edit_Y.text)),Number(edit_angle.text),Number(edit_density.text),Number(edit_friction.text),Number(edit_scaleX.text),Number(edit_scaleY.text),Number(edit_restitution.text),isSensor);
		             domin.addEventListener(OutOfScreen.OUT_DOMIN,removeHandler);
					 }
		if(actDomin is actorDomino){
		             domin = new actorDomino(m_world, this, new Point(Number(edit_X.text), Number(edit_Y.text)),Number(edit_angle.text),Number(edit_density.text),Number(edit_friction.text),Number(edit_scaleX.text),Number(edit_scaleY.text),Number(edit_restitution.text),isSensor);
		             domin.addEventListener(OutOfScreen.OUT_DOMIN,removeHandler);
					 }
 		if(actDomin is actorCircle){
		             domin = new actorCircle(m_world, this,new Point(Number(edit_X.text), Number(edit_Y.text)),Number(edit_angle.text),Number(edit_density.text),Number(edit_friction.text),Number(edit_scaleX.text),Number(edit_scaleY.text),Number(edit_restitution.text),isSensor);
		             domin.addEventListener(OutOfScreen.OUT_DOMIN,removeHandler);
					 }
		if(actDomin is actorCross)
		             domin = new actorCross(m_world, this,new Point(Number(edit_X.text), Number(edit_Y.text)),Number(edit_angle.text),Number(edit_density.text),Number(edit_friction.text),Number(edit_scaleX.text),Number(edit_scaleY.text),Number(edit_restitution.text),Number(edit_angV.text),isSensor);

		if(actDomin is actorAngle)
		             domin = new actorAngle(m_world, this,new Point(Number(edit_X.text), Number(edit_Y.text)),Number(edit_angle.text),Number(edit_density.text),Number(edit_friction.text),Number(edit_scaleX.text),Number(edit_scaleY.text),Number(edit_restitution.text),Number(edit_angV.text),isSensor);
				 
		if(actDomin is actorCoin)
		             domin = new actorCoin(m_world, this,new Point(Number(edit_X.text), Number(edit_Y.text)),Number(edit_angle.text),Number(edit_density.text),Number(edit_friction.text),Number(edit_scaleX.text),Number(edit_scaleY.text),Number(edit_restitution.text));
		
		if(actDomin is actorTrident)
		             domin = new actorTrident(m_world, this,new Point(Number(edit_X.text), Number(edit_Y.text)),Number(edit_angle.text),Number(edit_density.text),Number(edit_friction.text),Number(edit_scaleX.text),Number(edit_scaleY.text),Number(edit_restitution.text),Number(edit_angV.text),isSensor);
		
		if(actDomin is actorTrident2)
		             domin = new actorTrident2(m_world, this,new Point(Number(edit_X.text), Number(edit_Y.text)),Number(edit_angle.text),Number(edit_density.text),Number(edit_friction.text),Number(edit_scaleX.text),Number(edit_scaleY.text),Number(edit_restitution.text),Number(edit_angV.text),isSensor);
		
		if(actDomin is actorPendulum)
		             domin = new actorPendulum(m_world, this,new Point(Number(edit_X.text), Number(edit_Y.text)),Number(edit_angle.text),Number(edit_density.text),Number(edit_friction.text),Number(edit_scaleX.text),Number(edit_scaleY.text),Number(edit_restitution.text),Number(edit_angV.text),isSensor);
		
		if(actDomin is actorPendulum2)
		             domin = new actorPendulum2(m_world, this,new Point(Number(edit_X.text), Number(edit_Y.text)),Number(edit_angle.text),Number(edit_density.text),Number(edit_friction.text),Number(edit_scaleX.text),Number(edit_scaleY.text),Number(edit_restitution.text),Number(edit_angV.text),isSensor);
					 
		 dominArray.push(domin);
		 actDomin = domin;
		 MovieClip(actDomin._costume).gotoAndStop(3);
		 
		trace("deleted old and created new domin");
		}
///////////////////////////////////
function reloadDomin() {
		
		trace(" reload domin");
		actDomin._body.SetXForm(new b2Vec2(int(edit_X.text) / 30, int(edit_Y.text) / 30), int(edit_angle.text) * Math.PI / 180 );
		//actDomin..SetXForm(new b2Vec2(int(edit_X.text)/30, int(edit_Y.text)/30),int(edit_angle.text)*Math.PI/180 );
		 
		
		if(actDomin is actorCross)
		             actorCross(actDomin).rev_joint.SetXForm(new b2Vec2(int(edit_X.text) / 30, int(edit_Y.text) / 30), int(edit_angle.text) * Math.PI / 180 );
		
		if(actDomin is actorAngle)
		             actorAngle(actDomin).rev_joint.SetXForm(new b2Vec2(int(edit_X.text) / 30, int(edit_Y.text) / 30), int(edit_angle.text) * Math.PI / 180 );
		
		if(actDomin is actorTrident)
		             actorTrident(actDomin).rev_joint.SetXForm(new b2Vec2(int(edit_X.text) / 30, int(edit_Y.text) / 30), int(edit_angle.text) * Math.PI / 180 );
		
		if(actDomin is actorTrident2)
		             actorTrident2(actDomin).rev_joint.SetXForm(new b2Vec2(int(edit_X.text) / 30, int(edit_Y.text) / 30), int(edit_angle.text) * Math.PI / 180 );
		
		if(actDomin is actorPendulum)
		             actorPendulum(actDomin).rev_joint.SetXForm(new b2Vec2(int(edit_X.text) / 30, int(edit_Y.text) / 30), int(edit_angle.text) * Math.PI / 180 );
		
		if(actDomin is actorPendulum2)
		             actorPendulum2(actDomin).rev_joint.SetXForm(new b2Vec2(int(edit_X.text) / 30, int(edit_Y.text) / 30), int(edit_angle.text) * Math.PI / 180 );
		
		 
		}
///////////////////////////////////
function removeDomino(dom:actor) { 
				trace("deleting of "+dom);
				 
				//if ((dom is actorDomino)||(dom is actorCircle) ||(dom is actorCross) || (dom is actorCoin)|| (dom is actorAngle)) 
					if(dom is actor){	
						var n:Number=dominArray.indexOf(dom);
						dominArray.splice(n,1);
						dom.removeActor(m_world);
						actDomin = null;
					 }
				 
				}
///////////////////////////////////
function removeDominos() {
		    	for each(var d:actor in dominArray ){
				 //if ((d is actorDomino)||(d is actorCircle)||(d is actorCross)|| (d is actorCoin) || (d is actorAngle))
				 if (d is actor)
				  if (d is actorWall)
				   continue;
				  dominToDelete.push(d);
                }
			} 
///////////////////////////////////
public function addCoord()
{
			 wallArray = [];
			 PointArray = [];

			 PointArray.push(new Point(1, 1));
			 PointArray.push(new Point(549, 1));
			 PointArray.push(new Point(549, 10));
			 PointArray.push(new Point(1, 10));
		     wallArray.push(PointArray);
			 PointArray = [];
			 
			 PointArray.push(new Point(1, 1));
			 PointArray.push(new Point(10, 1));
			 PointArray.push(new Point(10, 399));
			 PointArray.push(new Point(1, 399));
		     wallArray.push(PointArray);
			 PointArray = [];
			 
			 PointArray.push(new Point(442, 1));
			 PointArray.push(new Point(452, 1));
			 PointArray.push(new Point(452, 399));
			 PointArray.push(new Point(442, 399));
		     wallArray.push(PointArray);
			 PointArray = [];
			 
			 PointArray.push(new Point(1, 389));
			 PointArray.push(new Point(549, 389));
			 PointArray.push(new Point(549, 399));
			 PointArray.push(new Point(1, 399));
		     wallArray.push(PointArray);
			 PointArray = [];
			 
		 }
////////////////////////////////////
public function createWorld():void {
		    var environment:b2AABB = new b2AABB();	
		    var gravity:b2Vec2 = new b2Vec2(0.0, 10.0);
		    environment.lowerBound.Set(-100.0, -100.0);
			environment.upperBound.Set(100.0, 100.0);
			m_world = new b2World(environment, gravity, true);	
			m_world.SetContactListener(new DominContactListener());
		}
///////////////////////////////////
public function GetRealWH(Num:Number) {
			return Num / physScale / 2;
		}
/////////////////////////////////////////
function fillEditBoxes(){
		 	 
		  var data:Array = [];
          
		    if(actDomin is actorTriangle)
				   data = actorTriangle(actDomin).getData();

		    if(actDomin is actorDomino)
				   data = actorDomino(actDomin).getData();  
			
		    if(actDomin is actorCircle)
				   data = actorCircle(actDomin).getData();

			if(actDomin is actorCross)
				   data = actorCross(actDomin).getData();
				   
			if(actDomin is actorCoin)
				   data = actorCoin(actDomin).getData();
				   
		    if(actDomin is actorAngle)
			       data = actorAngle(actDomin).getData();
				   
			if(actDomin is actorTrident)
			       data = actorTrident(actDomin).getData();
			
			if(actDomin is actorTrident2)
			       data = actorTrident2(actDomin).getData();
				   
			if(actDomin is actorPendulum)
			       data = actorPendulum(actDomin).getData();
			
			if(actDomin is actorPendulum2)
			       data = actorPendulum2(actDomin).getData();
			

	    edit_X.text = data[0];
        edit_Y.text = data[1];
		edit_scaleX.text = data[2];
    	edit_scaleY.text = data[3];
	    edit_friction.text = data[4];
		edit_density.text = data[5];
		edit_angle.text = data[6];
		edit_restitution.text = data[7];
		edit_angV.text = data[8];
		
		

		/*edit_X.text = String(Math.round(data[0]));
        edit_Y.text = String(Math.round(data[1]));
		edit_scaleX.text = String(Math.round(data[2]/.01)*.01);
    	edit_scaleY.text = String(Math.round(data[3]/.01)*.01);
	    edit_friction.text = String(Math.round(data[4]/.1)*.1);
		edit_density.text = String(Math.round(data[5]/.1)*.1);
		edit_angle.text = String(Math.round(data[6]));*/
	}
/////////////////////////////////////////
function checkMousePosition():Boolean {
	if (!redact)
	 return null;
	 
//main field	 
	if ((stage.mouseX >= 0) && (stage.mouseY >=24) && (stage.mouseX < 552) && (stage.mouseY < 480)){
	 dispatchEvent(new MainField(MainField.MOUSE_IN_FIELD));
	 return true;
	}
//menu field	
	if ((stage.mouseX > 640) && (stage.mouseY >=0) && (stage.mouseX < 788) && (stage.mouseY < 480)) {
	 dispatchEvent(new MainField(MainField.MOUSE_IN_FIGURES));
	 return true;
	 }
//select figure
    if ((stage.mouseX >= 552) && (stage.mouseY >=0) && (stage.mouseX <=640) && (stage.mouseY < 480)) {
	 dispatchEvent(new MainField(MainField.MOUSE_IN_SELECT));
	 return true;
	 }
	return false; 
	}
/////////////////////////////////////////
public function Update(e:Event):void {
		 
		 if(run)
		   m_world.Step(m_timeStep, m_iterations);
		   
		  aboveMouse = GetBodyAtMouse(); 
		  if(aboveMouse){
		   if ( aboveMouse.GetUserData()){
		      arrowSprite.x = stage.mouseX;
		      arrowSprite.y = stage.mouseY;
			  arrowSprite.visible = true;
			  arrowSprite.rotation =  180 / Math.PI * aboveMouse.GetUserData().GetArrowAngle(new Point(stage.mouseX, stage.mouseY), new Point(aboveMouse.GetPosition().x*30,aboveMouse.GetPosition().y*30)) ;
		    }
		  }
		  else 
			  arrowSprite.visible = false;	  
		  

		    markToRemoveDomins();
		    realDominsDeleting();
			dominToDelete = [];
			
			for each(var something:actor in dominArray)
			  something.update();	
		}
///////////////////////////
function markToRemoveDomins() {
		var nToDel:int;
		var n:int;
		if (dominToDelete.length > 0){
		  for each(var domToDel:actor in dominToDelete)
		   {
			n = dominArray.indexOf(domToDel);
			if(n!=-1)
		       dominArray.splice(n, 1);
		   }

		 }
		}
//////////////////////////////////////////	
function realDominsDeleting() {
			if (dominToDelete.length > 0){
			 for each(var domToDel2:actor in dominToDelete )  
			  domToDel2.removeActor(m_world);
		
			}			 
		}	
//////////////////////////
public function getPos():Point {
		
		var cenPos:Point = new Point(aboveMouse.GetPosition().x,aboveMouse.GetPosition().y);
		return cenPos; 
		}
///////////////////////////
public function GetBodyAtMouse():b2Body {
			real_x_mouse = (stage.mouseX)/pixels_in_a_meter;
			real_y_mouse = (stage.mouseY)/pixels_in_a_meter;
			
			mousePVec.Set(real_x_mouse, real_y_mouse);
			var aabb:b2AABB = new b2AABB();
			aabb.lowerBound.Set(real_x_mouse - 0.001, real_y_mouse - 0.001);
			aabb.upperBound.Set(real_x_mouse + 0.001, real_y_mouse + 0.001);
			var k_maxCount:int = 10;
			var shapes:Array = new Array();
			var count:int = m_world.Query(aabb, shapes, k_maxCount);
			var body:b2Body = null;
			
			for (var i:int = 0; i < count; ++i) {
				    var tShape:b2Shape = shapes[i] as b2Shape;
					var inside:Boolean = tShape.TestPoint(tShape.m_body.GetXForm(), mousePVec);
					
					if (inside) {
						body = tShape.m_body;
						body_number=i;
						break;
					}
				}	
			 	
			return body;
		}	

///////////////////
public function clickListener(e2:MouseEvent):Boolean {   
	 
	checkMousePosition();//this function generate events and selects domins
// addChild(new angle2());
  // trace(actDomin._body.GetPosition().x*30 + " body " + actDomin._body.GetPosition().y*30);
   //trace(stage.mouseX + " mouse " + stage.mouseY);
				  
	if ((actDomin)&&(run==true)&&(aboveMouse)){  //push domino
			   actDomin.moveDomino(new Point(stage.mouseX, stage.mouseY));
			 //  trace("actDomin" + actDomin.isSensor);
	    }
			return true;
		 	 }
//////////////////////////////////////
function createDomin() {
	trace("create some");
	           if ((redact == true) && (typeFigure != "")) {   
				   
					if (typeFigure == "[object actorDomino]") {
		             domin = new actorDomino(m_world, this, new Point(stage.mouseX, stage.mouseY),Number(edit_angle.text),Number(edit_density.text),Number(edit_friction.text),Number(edit_scaleX.text),Number(edit_scaleY.text),Number(edit_restitution.text),isSensor);
					 domin.addEventListener(OutOfScreen.OUT_DOMIN, removeHandler);
			         domin._body.GetShapeList().IsSensor();
				
					 }
			   
					 if (typeFigure == "[object actorTriangle]") {
		             domin = new actorTriangle(m_world, this, new Point(stage.mouseX, stage.mouseY),Number(edit_angle.text),Number(edit_density.text),Number(edit_friction.text),Number(edit_scaleX.text),Number(edit_scaleY.text),Number(edit_restitution.text),isSensor);
					 domin.addEventListener(OutOfScreen.OUT_DOMIN, removeHandler);
			         domin._body.GetShapeList().IsSensor();
				
					 }	 
				    if(typeFigure=="[object actorCircle]"){
		             domin = new actorCircle(m_world, this,new Point(stage.mouseX, stage.mouseY),Number(edit_angle.text),Number(edit_density.text),Number(edit_friction.text),Number(edit_scaleX.text),Number(edit_scaleY.text),Number(edit_restitution.text),isSensor);
					 domin.addEventListener(OutOfScreen.OUT_DOMIN,removeHandler);
					 }
					if (typeFigure == "[object actorCross]")
					 domin = new actorCross(m_world, this,new Point(stage.mouseX, stage.mouseY),Number(edit_angle.text),Number(edit_density.text),Number(edit_friction.text),Number(edit_scaleX.text),Number(edit_scaleY.text),Number(edit_restitution.text),Number(edit_angV.text),isSensor);
		            
					 if (typeFigure == "[object actorAngle]")
                      domin = new actorAngle(m_world, this,new Point(stage.mouseX, stage.mouseY),Number(edit_angle.text),Number(edit_density.text),Number(edit_friction.text),Number(edit_scaleX.text),Number(edit_scaleY.text),Number(edit_restitution.text),Number(edit_angV.text),isSensor);  
					 
					 if (typeFigure == "[object actorTrident]")
                      domin = new actorTrident(m_world, this,new Point(stage.mouseX, stage.mouseY),Number(edit_angle.text),Number(edit_density.text),Number(edit_friction.text),Number(edit_scaleX.text),Number(edit_scaleY.text),Number(edit_restitution.text),Number(edit_angV.text),isSensor);  
					 
					 if (typeFigure == "[object actorTrident2]")
                      domin = new actorTrident2(m_world, this,new Point(stage.mouseX, stage.mouseY),Number(edit_angle.text),Number(edit_density.text),Number(edit_friction.text),Number(edit_scaleX.text),Number(edit_scaleY.text),Number(edit_restitution.text),Number(edit_angV.text),isSensor);  
					  
					 if (typeFigure == "[object actorPendulum]")
                      domin = new actorPendulum(m_world, this,new Point(stage.mouseX, stage.mouseY),Number(edit_angle.text),Number(edit_density.text),Number(edit_friction.text),Number(edit_scaleX.text),Number(edit_scaleY.text),Number(edit_restitution.text),Number(edit_angV.text),isSensor);  
					 
					 if (typeFigure == "[object actorPendulum2]")
                      domin = new actorPendulum2(m_world, this,new Point(stage.mouseX, stage.mouseY),Number(edit_angle.text),Number(edit_density.text),Number(edit_friction.text),Number(edit_scaleX.text),Number(edit_scaleY.text),Number(edit_restitution.text),Number(edit_angV.text),isSensor);  
					 
					 if(typeFigure=="[object actorCoin]"){
		             domin = new actorCoin(m_world, this,new Point(stage.mouseX, stage.mouseY),Number(edit_angle.text),Number(edit_density.text),Number(edit_friction.text),Number(edit_scaleX.text),Number(edit_scaleY.text),Number(edit_restitution.text));
	                 coins++;
					 domin.addEventListener(takeCoin.TAKE_COIN,coinHandler);
					}
					 actDomin = domin;
				     dominArray.push(domin);
					 trace("created new figure");
			       }
	}
////////////////////////////////////////////////////////	
	private function removeHandler(e:OutOfScreen):void 
	{
	 trace("delete domin");
	 dominToDelete.push(e.currentTarget);
	}
//////////////////////////////////
function coinHandler(e:takeCoin) {
	trace("delete coin");
	dominToDelete.push(e.currentTarget);
	coins--;
	coin.text = String(coins);
	}
/////////////////////////////////	after full xml loading
public function completeListener(e:Event):void{
			  levelsDoc = new XML(urlLoad.data);	
			  IO_XML = new IOXML(levelsDoc);
			  }
///////////////////////////////////////	
function setDominColor():Boolean {
			
		    if (actDomin == null)  
				return false;
			
			if (temp_domin == actDomin){
			    MovieClip(actDomin._costume).gotoAndStop(3);
			    return true;
			}
			else { 

				MovieClip(actDomin._costume).gotoAndStop(3);
				 
				if(temp_domin is actorDomino) {
				  if(actorDomino(temp_domin).density!=0)
				   MovieClip(temp_domin._costume).gotoAndStop(1);
				else
				   MovieClip(temp_domin._costume).gotoAndStop(2);
				 }   
				 
				if(temp_domin is actorTriangle) {
				  if(actorTriangle(temp_domin).density!=0)
				   MovieClip(temp_domin._costume).gotoAndStop(1);
				else
				   MovieClip(temp_domin._costume).gotoAndStop(2);
				 }   
				 
				 
				if(temp_domin is actorCircle) {
				  if(actorCircle(temp_domin).density!=0)
				    MovieClip(temp_domin._costume).gotoAndStop(1);
				  else
				    MovieClip(temp_domin._costume).gotoAndStop(2); 
				  }
				 
				 if(temp_domin is actorCoin) {
				  if(actorCoin(temp_domin).density!=0)
				    MovieClip(temp_domin._costume).gotoAndStop(1);
				  else
				    MovieClip(temp_domin._costume).gotoAndStop(2); 
				  }
				  
				 if(temp_domin is actorCross) {
				  if(actorCross(temp_domin).density!=0)
				    MovieClip(temp_domin._costume).gotoAndStop(1);
				  else
				    MovieClip(temp_domin._costume).gotoAndStop(2); 
				  } 
				  
				   if (temp_domin is actorAngle ) {
				     if(actorAngle(temp_domin).density!=0)
				       MovieClip(temp_domin._costume).gotoAndStop(1);
				   else
				     MovieClip(temp_domin._costume).gotoAndStop(2); 
				   }
					 
					if (temp_domin is actorTrident ) {
				     if(actorTrident(temp_domin).density!=0)
				       MovieClip(temp_domin._costume).gotoAndStop(1);
				    else
				     MovieClip(temp_domin._costume).gotoAndStop(2);
					}
					
					if (temp_domin is actorTrident2 ) {
				     if(actorTrident2(temp_domin).stat!=0)
				       MovieClip(temp_domin._costume).gotoAndStop(1);
				    else
				     MovieClip(temp_domin._costume).gotoAndStop(2);  
					}
					if (temp_domin is actorPendulum ) {
				     if(actorPendulum(temp_domin).density!=0)
				       MovieClip(temp_domin._costume).gotoAndStop(1);
				    else
				     MovieClip(temp_domin._costume).gotoAndStop(2);  
					}
					
					if (temp_domin is actorPendulum2 ) {
				     if(actorPendulum2(temp_domin).density!=0)
				       MovieClip(temp_domin._costume).gotoAndStop(1);
				    else
				     MovieClip(temp_domin._costume).gotoAndStop(2);  
					}
				  
				  
			    temp_domin = actDomin; 
				return true;
			}
			
		}
////////////////////////////////////////
public function  addArrow() {
			 arrowSprite = new arrow();
			 arrowSprite.x = -10;
			 arrowSprite.y = -10;
			 stage.addChild(arrowSprite);
			}
///////////////////
public function IO(path_to_xml:String):void {
		    urlReq = new URLRequest(path_to_xml);
			urlLoad = new URLLoader();
			urlLoad.addEventListener(Event.COMPLETE,completeListener)
			urlLoad.load(urlReq);
		}
////////////////////////
 }
}